#include "gameroom.h"
#include<QPixmap>
#include<QIcon>
#include<QPainter>
#include<QTimer>
#include<QPushButton>
#include<QSound>
#include <QMediaPlayer>
#include<QMessageBox>
#include<QPen>
#include<QFile>
#include"gameselect.h"
Gameroom::Gameroom(QWidget *parent) : QWidget(parent)
{
    this->setFixedSize(1000,800);
    this->setWindowIcon(QIcon(":image/snake.png"));
    this->setWindowTitle("游戏界面");
    //初始化
    snakeList.push_back(QRectF(this->width()*0.5,this->height()*0.5,Nsnakewidth,Nsnakeheight));
    moveup();
    moveup();

    //创建食物
    creatfood();

    timer=new QTimer(this);
    connect(timer,&QTimer::timeout,[=](){
                    int meet=1;
                    if(snakeList.front().intersects(food))
                    {
                        creatfood();
                        meet++;
                    }
                    while(meet--)
                    {
                        switch (moveDirect) {
                        case SnakeDirect::UP:
                            moveup();
                            break;
                        case SnakeDirect::DOWN:
                            movedown();
                            break;
                        case SnakeDirect::LEFT:
                            moveleft();
                            break;
                        case SnakeDirect::RIGHT:
                            moveright();
                            break;
                        }
                    }
                    snakeList.pop_back();
                    update();
    });

    //开始，暂停按钮
    QPushButton*start=new QPushButton(this);
    QPushButton*stop=new QPushButton(this);
     QFont font("楷体",24);
     start->setFont(font);
     stop->setFont(font);
     start->setText("开始游戏");
     stop->setText("暂停游戏");
     start->setStyleSheet("QPushButton { border: 2px solid black; border-radius: 10px;background-color:grey; color:black;}");
     stop->setStyleSheet("QPushButton { border: 2px solid black; border-radius: 10px; background-color:grey;color:black;}");
     start->move(820,150);
     stop->move(820,240);
     //关联按钮和游戏
     connect(start,&QPushButton::clicked,[=](){
         isGameStart=true;
         timer->start(Vsnake);
         bgm=new QSound(":image/gamebgm.wav");
        bgm->play();
       bgm->setLoops(-1);
     });
     connect(stop,&QPushButton::clicked,[=](){
         isGameStart=false;
         timer->stop();
         bgm->stop();
     });

     //方向控制
     QPushButton*up=new QPushButton("&w",this);
     QPushButton*down=new QPushButton("&s",this);
     QPushButton*left=new QPushButton("&a",this);
     QPushButton*right=new QPushButton("&d",this);
     up->move(880,500);
     down->move(880,550);
     left->move(830,525);
     right->move(930,525);
//     up->setText("↑");
//     down->setText("↓");
//     left->setText("←");
//     right->setText("→");
     up->setStyleSheet("QPushButtom{border:0px;}");
     down->setStyleSheet("QPushButtom{border:0px;}");
     left->setStyleSheet("QPushButtom{border:0px;}");
     right->setStyleSheet("QPushButtom{border:0px;}");

     up->setFlat(true);
     down->setFlat(true);
     left->setFlat(true);
     right->setFlat(true);

     up->setIcon(QIcon(":image/up.png"));
     down->setIcon(QIcon(":image/down.png"));
     left->setIcon(QIcon(":image/left.png"));
     right->setIcon(QIcon(":image/right (2).png"));

     //关联四个按钮和游戏实现
     connect(up,&QPushButton::clicked,[=](){
         if(moveDirect!=SnakeDirect::DOWN)
         {
             moveDirect=SnakeDirect::UP;
         }
     });
     connect(down,&QPushButton::clicked,[=](){
         if(moveDirect!=SnakeDirect::UP)
         {
             moveDirect=SnakeDirect::DOWN;
         }
     });  connect(left,&QPushButton::clicked,[=](){
         if(moveDirect!=SnakeDirect::RIGHT)
         {
             moveDirect=SnakeDirect::LEFT;
         }
     });  connect(right,&QPushButton::clicked,[=](){
         if(moveDirect!=SnakeDirect::LEFT)
         {
             moveDirect=SnakeDirect::RIGHT;
         }
     });

     //退出游戏
     QPushButton*exit=new QPushButton(this);
     exit->setText("退出");
     exit->move(860,750);
     exit->setFont(font);
     exit->setStyleSheet("QPushButton { border: 2px solid black; border-radius: 10px; }");
     QMessageBox*box=new QMessageBox(this);
     box->setWindowTitle("退出游戏");
     box->setText("确认退出游戏吗？");
     QPushButton*ok=new QPushButton("确定");
     QPushButton*cancel=new QPushButton("取消");
     box->addButton(ok,QMessageBox::AcceptRole);
     box->addButton(cancel,QMessageBox::RejectRole);
     connect(exit,&QPushButton::clicked,[=](){
                    box->show();
                    box->exec();
                    QSound::play(":image/clicked.wav");
                    GameSelect *select=new GameSelect;
                    if(box->clickedButton()==ok){
                        this->close();

                        select->show();
                    }
                    else{
                        box->close();
                    }

     });
}

void Gameroom::paintEvent(QPaintEvent *event)
{
    (void)event;
    QPainter painter(this);
    QPixmap pixmap;
    pixmap.load(":image/gamebackground.png");
    painter.drawPixmap(0,0,800,800,pixmap);
     QPixmap pixmap2(":image/gameback2.png");
      painter.drawPixmap(800,0,200,800,pixmap2);


      //蛇的绘制 蛇头+蛇身+尾巴
      if(moveDirect==SnakeDirect::UP)
      {
          pixmap.load(":image/moveUP.png");
      }
      else if(moveDirect==SnakeDirect::DOWN)
      {
          pixmap.load(":image/moveDOWN.png");
      }
      else if(moveDirect==SnakeDirect::LEFT)
      {
          pixmap.load(":image/moveLEFT.png");
      }
     else
      {
          pixmap.load(":image/moveRIGHT.png");
      }
       auto head= snakeList.front();
       painter.drawPixmap(head.x(),head.y(),head.width(),head.height(),pixmap);
      //身体
      pixmap.load(":image/snakeBody.png");
     for(int i=1;i<snakeList.size()-1;i++){
         auto Node=snakeList.at(i);
         painter.drawPixmap(Node.x(),Node.y(),Node.width(),Node.height(),pixmap);
     }

     //尾巴
     auto tail=snakeList.back();
     painter.drawPixmap(tail.x(),tail.y(),tail.width(),tail.height(),pixmap);


     //绘制食物
     pixmap.load(":image/food.png");
     painter.drawPixmap(food.x(),food.y(),food.width(),food.height(),pixmap);

     //绘制得分
     pixmap.load(":image/score.png");
     painter.drawPixmap(850,30,100,100,pixmap);
    QPen pen;
    pen.setColor(Qt::black);
    painter.setPen(pen);
    QFont font("宋体",22);
    painter.setFont(font);
    painter.drawText(892,100,QString::number(snakeList.size()));
    //把得分写入文件中
    QFile file("C:/Users/12443/Desktop/snake/snake/score.txt");
    file.open(QIODevice::ReadWrite | QIODevice::Text);
    int size = snakeList.size();
    QString str = QString::number(size);
    file.write(str.toUtf8());
    file.close();
    //绘制游戏失败
    if(isGameover())
    {
        pen.setColor(Qt::red);
        painter.setPen(pen);
        QFont font("宋体",50);
        painter.drawText(this->width()*0.5,this->height()*0.5,"GAME OVER!");
        bgm->stop();
        QSound::play(":image/gameover.wav");
        timer->stop();
    }

}


void Gameroom::moveup()
{
    QPointF leftTop;
    QPointF rightButtom;//左上角和右下角坐标
    auto Nsnake=snakeList.front();//蛇的头
    int headX=Nsnake.x();
    int headY=Nsnake.y();
    if(headY<0)//碰到墙壁了
    {
        leftTop=QPointF(headX,this->height()-Nsnakeheight);
    }
    else{
        leftTop=QPointF(headX,headY-Nsnakeheight);
    }
    rightButtom=leftTop+QPointF(Nsnakewidth,Nsnakeheight);//右下角坐标一直等于左上角坐标加宽和高
      snakeList.push_front(QRectF(leftTop,rightButtom));
}

void Gameroom::movedown()
{
    QPointF leftTop;
    QPointF rightButtom;//左上角和右下角坐标
    auto Nsnake=snakeList.front();//蛇的头
    int headX=Nsnake.x();
    int headY=Nsnake.y();
    if(headY>800)//超出窗口的下边界
    {
        leftTop=QPointF(headX,0);
    }
    else{
        leftTop=Nsnake.bottomLeft();
    }
    rightButtom=leftTop+QPointF(Nsnakewidth,Nsnakeheight);
     snakeList.push_front(QRectF(leftTop,rightButtom));
}

void Gameroom::moveleft()
{
    QPointF leftTop;
    QPointF rightButtom;//左上角和右下角坐标
    auto Nsnake=snakeList.front();//蛇的头
    int headX=Nsnake.x();//蛇头的左上角坐标
    int headY=Nsnake.y();
    if(headX<0)
    {
        leftTop=QPointF(800-Nsnakewidth,headY);
    }
    else{
        leftTop=QPointF(headX-Nsnakewidth,headY);
    }
    rightButtom=leftTop+QPointF(Nsnakewidth,Nsnakeheight);
    snakeList.push_front(QRectF(leftTop,rightButtom));
}

void Gameroom::moveright()
{
    QPointF leftTop;
    QPointF rightButtom;//左上角和右下角坐标
    auto Nsnake=snakeList.front();//蛇的头
    int headX=Nsnake.x();//蛇头的左上角坐标
    int headY=Nsnake.y();
    if(headX+Nsnakewidth*2>800)
    {
        leftTop=QPointF(0,headY);
    }
    else{
        leftTop=Nsnake.topRight();
    }
    rightButtom=leftTop+QPointF(Nsnakewidth,Nsnakeheight);
    snakeList.push_front(QRectF(leftTop,rightButtom));
}

bool Gameroom::isGameover()
{
    for(int i=0;i<snakeList.size();i++)
   {
        for(int j=i+1;j<snakeList.size();j++)
            if(snakeList.at(i)==snakeList.at(j))
            {
                return true;
            }
    }
    return false;
}

void Gameroom::creatfood()
{
    food=QRect(qrand()%(800/Nsnakewidth)*Nsnakewidth,
                         qrand()%(this->height()/Nsnakeheight)*Nsnakeheight,
                          Nsnakewidth,
                         Nsnakeheight);
}
